var Permission = function () {

    var AddBtn = function ($modal) {
        $('.add-btn').on('click', function(){

            $('body').modalmanager('loading');
            
            var reload = $(this).parent().parent().find('a.reload').first();

            $modal.load($(this).attr('data-url'), function(){
                $modal.modal().on("hidden", function() {
                    $modal.empty();
                    reload.trigger('click');
                });
            });
        });
    };

    var EditBtn = function ($modal) {
        
        $( "body" ).on( "click", ".btn-edit", function() {
            $('body').modalmanager('loading');
            
            var reload = $(this).parent().parent().parent().parent().parent().parent().parent().find('a.reload').first();

            $modal.load($(this).attr('data-url'), function(){
                $modal.modal().on("hidden", function() {
                    $modal.empty();
                    reload.trigger('click');
                });
            });
        });
    };

    var RemoveBtn = function () {
        $( "body" ).on( "click", ".btn-remove", function() {
            
            var reload = $(this).parent().parent().parent().parent().parent().parent().parent().find('a.reload').first();
            
            $.ajax({
                url: $(this).attr('data-url'),
                type: 'post',
                dataType: 'json'
            }).done(function(response) {
                reload.trigger('click');
            })
            .fail(function() {
                alert('Check Your Connection.');
            });
        });
    };

    var LoadData = function () {
        $( "div.tabbable-custom ul li a" ).click(function () {
            if ($('table', 'div' + $(this).attr('href')).length == 0 ) {
                $('.reload', 'div' + $(this).attr('href')).click();
            }
        }).first().trigger('click');
    };

    var handleOrders = function() {
        var table = $("#datatable_list");
        var grid = new Datatable();
        grid.init({
            src: table,
            onSuccess: function(grid) {
            // execute some code after table records loaded
            },
            onError: function(grid) {
            // execute some code on network or other general error  
            },
            dataTable: {  // here you can define a typical datatable settings from http://datatables.net/usage/options 
                'sAjaxSource' :table.attr('action'),
                "aoColumns": [
                {
                    "mDataProp": "checkbox"
                },
                {
                    "mDataProp": "user_id"
                },
                {
                    "mDataProp": "username"
                },
                {
                    "mDataProp": "rolename"
                },
                {
                    "mDataProp": "actions"
                },
                ],
                "aoColumnDefs" : [
                {
                    'bSortable' : false,
                    'aTargets' : [0,1,2,3,4]
                }
                ],
                "bServerSide": true
            }
        });
        
        // handle filter
        grid.getDataTable().on('change', '.form-filter[name^="filter_"]', function(e){
            $('.filter-submit', grid.getDataTable()).trigger('click');
        });
        
        grid.getTableWrapper().on('change', '.table-group-action-input', function(e){
            if ($(this).val() == 'setclass') {
                $(this).parent().find('.setclass').show();
            }
            else {
                $(this).parent().find('.setclass').hide();
            }
        });

        // handle group actionsubmit button click
        grid.getTableWrapper().on('click', '.table-group-action-submit', function(e){
            e.preventDefault();
            var action = $(".table-group-action-input", grid.getTableWrapper());
            if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
                grid.addAjaxParam("sAction", "group_action");
                grid.addAjaxParam("sGroupActionName", action.val());
                var records = grid.getSelectedRows();
                for (var i in records) {
                    grid.addAjaxParam(records[i]["name"], records[i]["value"]);    
                }
                
                if (action.val() == 'setclass') {
                    grid.addAjaxParam('class_id', $('.setclass', grid.getTableWrapper()).val() );    
                }
                
                grid.getDataTable().fnStandingRedraw();
                grid.removeAjaxParam('sAction');
                grid.removeAjaxParam('sGroupActionName');
                grid.removeAjaxParam('class_id');
                for (var i in records) {
                    grid.removeAjaxParam(records[i]["name"]);
                }
            } else if (action.val() == "") {
                Metronic.alert({
                    type: 'danger', 
                    icon: 'warning', 
                    message: $('input:hidden.error-no-action').val(), 
                    container: grid.getTableWrapper(), 
                    place: 'prepend'
                });
            } else if (grid.getSelectedRowsCount() === 0) {
                Metronic.alert({
                    type: 'danger', 
                    icon: 'warning', 
                    message: $('input:hidden.error-no-item').val(), 
                    container: grid.getTableWrapper(), 
                    place: 'prepend'
                });
            }
        });
        
    }
    
    return {

        init: function () {
            
            $.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner = 
            '<div class="loading-spinner" style="width: 200px; margin-left: -100px;">' +
            '<div class="progress progress-striped active">' +
            '<div class="progress-bar" style="width: 100%;"></div>' +
            '</div>' +
            '</div>';
            
            $.fn.modalmanager.defaults.resize = true;
            
            var $modal = $('#ajax-modal');
            
            handleOrders();
            AddBtn($modal);
            EditBtn($modal);
            RemoveBtn();
            LoadData();
        }

    };

}();